import {Divider, Popconfirm, Table, Input, Select} from 'antd'
import React, {useState, useEffect} from 'react'
import styles from "@/pages/Info/Edit/style.less";
import {awardTypeList} from '@/utils/constant'
import {formatNumber} from "@/utils/utils";

const {Option} = Select;

const TableForm = ({orgList, onChange, list, delOrgId = '000000000'}) => {
  const [clickedCancel, setClickedCancel] = useState(false);
  const [loading, setLoading] = useState(false);
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [data, setData] = useState([]);
  const [tempData, setTempData] = useState([]);

  useEffect(() => {
    let t = tempData.filter(item => item.orgId.toString() !== delOrgId.toString());
    let newTempData = [...t];
    orgList.forEach((item) => {
      let pushFlag = true;
      t.forEach(hadItem => {
        if (hadItem.orgId.toString() === item.value.toString()) {
          pushFlag = false;
        }
        hadItem.editable = false;
      });
      if (pushFlag) {
        newTempData.push({
          orgname: item.children,
          orgId: item.value,
          key: item.value,
          awardType: null,
          distributionAmount: null
        })
      }
    });
    setData(newTempData);
    setTempData(newTempData);
    onChange(data);
  }, [orgList]);


  useEffect(() => {
    if (list.length > 0) {
      let t = tempData.length > 0 ? tempData.filter(item => item.orgId.toString() !== delOrgId.toString()) : list;
      let newTempData = [...t];
      list.forEach((item) => {
        let pushFlag = true;
        item.key = item.orgId;
        t.forEach(hadItem => {
          if (hadItem.orgId.toString() === item.orgId.toString()) {
            pushFlag = false;
          }
          hadItem.editable = false;
        });
        if (pushFlag) {
          newTempData.push({
            orgname: item.orgname,
            orgId: item.orgId,
            key: item.orgId,
            awardType: null,
            distributionAmount: null
          })
        }
      });
      setData(newTempData);
      setTempData(newTempData);
      onChange(data);
    }
  }, [list]);


  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0];

  const toggleEditable = (e, key) => {
    e.preventDefault();
    const newData = data?.map((item) => ({...item}));
    const target = getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = {...target};
        setCacheOriginData(cacheOriginData)
      }
      target.editable = !target.editable;
      setData(newData);
      setTempData(newData);
    }
  };

  const remove = (e, key) => {
    const newData = [...data];
    let datas = newData.filter(item => item.key != key);
    setData(datas);
    setTempData(datas);
  };

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data];
    const target = getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e.target ? e.target.value : e;
      setData(newData);
      setTempData(newData);
    }
  };

  const updateRow = (e, rowKey) => {
    e.persist();
    if (clickedCancel) {
      setClickedCancel(false);
      return
    }
    const target = getRowByKey(rowKey) || {};
    toggleEditable(e, rowKey);
    const {isNew, editable, key, ...payload} = target;
    onChange(data);
    setTempData(data);
  };

  const cancel = (e, key) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...data];// 编辑前的原始数据
    let cacheData = [];
    cacheData = newData.map((item) => {
      if (item.key === key) {
        if (cacheOriginData[key]) {
          const originItem = {...item, ...cacheOriginData[key], editable: false};
          delete cacheOriginData[key]
          setCacheOriginData(cacheOriginData)
          return originItem
        }
      }
      return item;
    });
    setData(cacheData);
    setClickedCancel(false);
    setTempData(cacheData);
  };

  const columns = [
    {
      title: '公司',
      dataIndex: 'orgname',
    },
    {
      title: '奖罚类型',
      dataIndex: 'awardType',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text} onChange={(e) => handleFieldChange(e, 'awardType', record.key)}>
              {awardTypeList.map((item, index) => {
                return (
                  <Option value={item.value} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = awardTypeList.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
    {
      title: '分配金额',
      dataIndex: 'distributionAmount',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input value={text} defaultValue={0} autoFocus
                   onChange={(e) => handleFieldChange(e, 'distributionAmount', record.key)} suffix="元"/>
          )
        }
        return (text != undefined ? formatNumber(text) : 0) + '元'
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }
        if (record.editable) {
          return (
            <span>
              <a onClick={(e) => updateRow(e, record.key)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.key)}>取消</a>
            </span>
          )
        }
        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否要删除此行？" cancelText='取消' okText='确认' onConfirm={(e) => remove(e, record.key)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      },
    },
  ];
  return (
    <>
      <Table
        loading={loading}
        columns={columns}
        dataSource={data}
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
      />
    </>
  )
};

export default TableForm

